<template>
  <el-form :inline="true" :model="queryForm" class="demo-form-inline">
    <el-form-item label="用户名:">
      <el-input
        v-model="queryForm.username"
        placeholder="请输入用户名"
        clearable
        style="width: 200px"
      />
    </el-form-item>

    <el-form-item label="邮箱:">
      <el-input v-model="queryForm.email" placeholder="请输入邮箱" clearable style="width: 200px" />
    </el-form-item>

    <el-form-item>
      <el-button type="primary" @click="querySubmit">查询</el-button>
    </el-form-item>
  </el-form>

  <div class="table-header">
    <span class="table-title">用户列表</span>
    <el-button type="primary" @click="addUserDialog = true" v-if="actions.includes('addUser')"
      >添加</el-button
    >
  </div>
  <el-table :data="tableData">
    <el-table-column prop="username" label="用户名">
      <template #default="{ row }">
        <el-link type="primary" :underline="false" @click="handleUserClick(row.id)">
          {{ row.username }}
        </el-link>
      </template>
    </el-table-column>
    <el-table-column prop="email" label="邮箱" />
    <el-table-column prop="status" label="状态" v-if="actions.includes('disableUser')">
      <template #default="{ row }">
        <el-switch v-model="row.status" @change="fetchDisableUser(row)" />
      </template>
    </el-table-column>

    <el-table-column label="操作">
      <template #default="{ row }">
        <el-button link type="primary" @click="resetPwd(row.id)" circle>重置密码</el-button>
        <el-button
          link
          type="primary"
          @click="openUpdateUserDialog(row)"
          circle
          v-if="actions.includes('updateUser')"
          >编辑</el-button
        >
        <el-button
          link
          type="danger"
          @click="fetchDeleteUser(row.id)"
          circle
          v-if="actions.includes('deleUser')"
          >删除</el-button
        >
      </template>
    </el-table-column>
  </el-table>

  <div class="pagination-container">
    <el-pagination
      v-if="page.total > 0"
      v-model:current-page="pageNumber"
      v-model:page-size="pageSize"
      :page-sizes="[10, 20, 30, 40, 50]"
      :size="pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="page.total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />
  </div>

  <el-dialog v-model="addUserDialog" title="添加用户" width="500">
    <el-form :model="addUserForm">
      <el-form-item label="用户名" :label-width="formLabelWidth">
        <el-input v-model="addUserForm.username" autocomplete="off" />
      </el-form-item>
      <el-form-item label="邮箱" :label-width="formLabelWidth">
        <el-input v-model="addUserForm.email" autocomplete="off" />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="addUserDialog = false">取消</el-button>
        <el-button type="primary" @click="fetchAddUser"> 确认 </el-button>
      </div>
    </template>
  </el-dialog>

  <el-dialog v-model="updateUserDialog" title="更新用户" width="500">
    <el-form :model="updateUserForm">
      <el-form-item label="用户名" :label-width="formLabelWidth">
        <el-input v-model="updateUserForm.username" autocomplete="off" />
      </el-form-item>
      <el-form-item label="邮箱" :label-width="formLabelWidth">
        <el-input v-model="updateUserForm.email" autocomplete="off" />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="updateUserDialog = false">取消</el-button>
        <el-button type="primary" @click="fetchUpdateUser(updateUserForm.id)"> 确认 </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { onMounted, ref, reactive } from 'vue'
import { listUser, addUser, deleteUser, updateUser, disableUser } from '@/api/user'
import type { PaginationParams } from '@/api/user'
import { ElMessage } from 'element-plus'
import { Delete, Edit } from '@element-plus/icons-vue'
import router from '@/router'
import { actions } from '@/api/auth'

const addUserDialog = ref(false)
const updateUserDialog = ref(false)
const formLabelWidth = '140px'
const page = reactive({ total: 0 })
const pageSize = ref(10)
const pageNumber = ref(1)

const initAddUserForm = reactive({
  username: '',
  email: ''
  // 添加其他字段
})

const addUserForm = reactive({ ...initAddUserForm })
const updateUserForm = reactive({ ...initAddUserForm })
const queryForm = reactive({ ...initAddUserForm })
const tableData = ref([])

//
const handleUserClick = (id: number) => {
  router.push(`/user/${id}/group`)
}

// 定义一个方法来获取用户列表
const fetchListUser = async (params: PaginationParams & { username?: string; email?: string }) => {
  try {
    const filteredParams = Object.fromEntries(
      Object.entries(params).filter(([key, value]) => value !== undefined && value !== '')
    )
    const res = await listUser(filteredParams)
    tableData.value = res.data.data
    page.total = res.data.total
  } catch (error) {
    ElMessage.error(error)
  }
}

const querySubmit = () => {
  pageNumber.value = 1
  fetchListUser({
    page: pageNumber.value,
    size: pageSize.value,
    username: queryForm.username,
    email: queryForm.email
  })
}

const openUpdateUserDialog = (row: any) => {
  // Object.assign(updateUserForm, row)
  updateUserForm.username = row.username
  updateUserForm.email = row.email
  updateUserForm.id = row.id // 需要确保 id 存在
  updateUserDialog.value = true
}

//禁用用户
const fetchDisableUser = async (row) => {
  try {
    const res = await disableUser({ id: [row.id], disable: row.status })
    if (res.status < 300) {
      if (row.status) {
        ElMessage.success('启用成功')
      } else {
        ElMessage.success('禁用成功')
      }
    } else {
      ElMessage.error('操作失败')
    }
  } catch (error) {
    ElMessage.error(error)
  }
}

const fetchAddUser = async () => {
  try {
    const res = await addUser(addUserForm)
    if (res.status < 300) {
      ElMessage.success('添加用户成功')
      addUserDialog.value = false
      Object.assign(addUserForm, initAddUserForm) //重置表单内容，不然会显示上次的内容
      // 提交成功后刷新用户列表
      pageNumber.value = 1
      fetchListUser({
        page: pageNumber.value,
        size: pageSize.value,
        username: queryForm.username,
        email: queryForm.email
      })
    } else {
      ElMessage.error('添加用户失败')
    }
  } catch (error) {
    ElMessage.error('添加用户失败')
    console.error('Failed to add user:', error)
  }
}
// 定义一个方法来更新用户
const fetchUpdateUser = async (id: string) => {
  try {
    const res = await updateUser(id, updateUserForm)
    if (res.status < 300) {
      ElMessage.success('更新用户成功')
      // 提交成功后刷新用户列表
      updateUserDialog.value = false
      pageNumber.value = 1
      fetchListUser({
        page: pageNumber.value,
        size: pageSize.value,
        username: queryForm.username,
        email: queryForm.email
      })
    } else {
      ElMessage.error('更新用户失败')
    }
  } catch (error) {
    console.error('Failed to update user:', error)
  }
}

// 定义一个方法来删除用户
const fetchDeleteUser = async (id: string) => {
  try {
    const res = await deleteUser(id)
    if (res.status < 300) {
      ElMessage.success('删除用户成功')
      // 提交成功后刷新用户列表
      pageNumber.value = 1
      fetchListUser({
        page: pageNumber.value,
        size: pageSize.value,
        username: queryForm.username,
        email: queryForm.email
      })
    } else {
      ElMessage.error('删除用户失败')
    }
  } catch (error) {
    ElMessage.error('删除用户失败')
    console.error('Failed to delete user:', error)
  }
}

// 使用 onMounted 在组件挂载后调用 fetchUserList 方法
onMounted(() => {
  fetchListUser({ page: pageNumber.value, size: pageSize.value })
})

const handleSizeChange = (size: number) => {
  pageSize.value = size
  pageNumber.value = 1 // 重置为第一页
  fetchListUser({
    page: pageNumber.value,
    size: pageSize.value,
    username: queryForm.username,
    email: queryForm.email
  })
}

const handleCurrentChange = (page: number) => {
  pageNumber.value = page
  fetchListUser({
    page: pageNumber.value,
    size: pageSize.value,
    username: queryForm.username,
    email: queryForm.email
  })
}
</script>

<style scoped>
.pagination-container {
  display: flex;
  justify-content: flex-end; /* 右对齐 */
  margin-top: 25px; /* 添加顶部间距 */
}
.demo-form-inline {
  margin-bottom: 20px;
}

.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.table-title {
  font-size: 18px;
  font-weight: bold;
}
</style>

